﻿namespace Pibby.Core.Persistence
{
	using System;
	using System.Collections.Generic;
	using System.Collections.ObjectModel;
	using System.Reflection;

	public class VersionSpecificScriptCollection : Collection<VersionSpecificScript>
	{
		/// <summary>
		/// Creates a list of update scripts that should be run to bring an "old" installation
		/// up to the current version of the supplied assembly
		/// </summary>
		/// <param name="assembly"></param>
		public void Populate(Assembly assembly, Version olderVersion)
		{
			string[] resourceNames = assembly.GetManifestResourceNames();
			var thisVersion = assembly.GetName().Version;

			this.Populate(thisVersion, olderVersion, resourceNames);
		}

		public void Populate(Version thisVersion, Version olderVersion, IEnumerable<string> resourceNames)
		{
			Contract.EnsureThat(olderVersion <= thisVersion, "Cannot update - the current version of the assembly is older than the version to upgrade from.");

			foreach (string resourceName in resourceNames)
			{
				var script = new VersionSpecificScript(resourceName);

				if (script.Version > olderVersion)
				{
					this.Add(script);
				}
			}
		}
	}
}
